package com.example.importtest.register;

import com.example.configuration.Teacher;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * ImportBeanDefinitionRegistrar比ImportSelector功能强大
 *
 * @author yanzhao
 * @date 2022/5/9 11:22
 * @since 1.0.0
 */
public class BeanRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * 手动注册bean到IOC容器
     *
     * @param importingClassMetadata
     * @param registry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableBeanRegistrar.class.getName()));
        String name = "";
        if (annotationAttributes != null) {
            name = annotationAttributes.getString("value");
        }
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Teacher.class.getName());
        builder.addPropertyValue("name", name);
        registry.registerBeanDefinition("teacher", builder.getBeanDefinition());
    }
}
